import { ajaxAsync, dateFtt } from 'vue-xiaobu-utils'
import RouteInfoModel from '../model/RouteInfoModel'
import StationInfoModel from '../model/StationInfoModel'
import BusInfoModel from '../model/BusInfoModel'
import DistanceModel from '../model/DistanceModel'
import NoticeModel from '../model/NoticeModel'
import { stationIsAttention, busIsAttention } from './busPlugin'

// 设置了到站提醒的站点列表 STATION_SORT 站点序号
// let attentionStationList = [
//   { LINE_ID: '1011', LINE_TYPE: 1, STATION_ID: '20', STATION_SORT: 12 }
// ]
// 设置了下车提醒的车辆列表
// let attentionBusList = [{ LINE_ID: '1011', LINE_TYPE: 1, BUS_ID: '浙G20521' }]

/**
 * 根据线路id获取站点列表
 * @param {Number} routeId 线路Id
 * @param {Number} direction 方向 1、上行；2、下行
 * @param {String} selectedStation 选中的站点
 */
async function getRouteInfo(routeId, direction, selectedStation) {
  let postData = {
    SUB_ROUTEID: routeId,
    CITY_CODE: window.cityCode,
    BUS_DIRECTION: direction
  }
  let body = await ajaxAsync('/bus/bus/querybus', postData)
  let stationList = body.BUS_STATIONS
  if (stationList && stationList.length > 0) {
    let routeModel = new RouteInfoModel(
      routeId,
      body.BUS_NAME,
      direction,
      body.DIRECTIONS,
      body.BUS_START_STATION,
      body.BUS_END_STATION,
      body.SEGMENT_ID
    )
    let stationModelList = []
    let selectedIndex = -1
    stationList.map((station, index) => {
      let stationModel = new StationInfoModel(
        station.DUALSERIAL_ID,
        station.STATION_ID,
        station.UNIQUE_STATIONID,
        station.STATION_NAME,
        station.LONGITUDE,
        station.LATITUDE,
        routeId,
        direction,
        index + 1
      )
      // attentionStationList.find(attentionStation => {
      //   if (
      //     attentionStation.LINE_ID === routeId &&
      //     attentionStation.LINE_TYPE === direction &&
      //     attentionStation.STATION_ID === stationModel.stationId
      //   ) {
      //     stationModel.setStationAttention(true)
      //     return true
      //   }
      // })

      stationModel.setStationAttention(stationIsAttention(stationModel))

      if (selectedStation && selectedStation.sameId === stationModel.sameId) {
        selectedIndex = index
        selectedStation = stationModel
      }
      stationModelList.push(stationModel)
    })
    return {
      routeInfo: routeModel,
      stationList: stationModelList,
      selectedIndex,
      selectedStation
    }
  } else {
    throw new Error('无站点数据')
  }
}

/**
 * 查询线路公告
 *
 * @param {Number} routeId 线路id
 * @param {Number} direction 方向id
 */
async function getRouteNotice(routeId, direction) {
  let body = await ajaxAsync('/bus/notice/detail/byRouteId', {
    SUB_ROUTEID: parseInt(routeId),
    BUS_DIRECTION: parseInt(direction)
  })
  let notice = null
  if (body.NOTICE_ID) {
    notice = new NoticeModel(
      body.NOTICE_ID,
      body.NOTICE_TITLE,
      body.NOTICE_CONTENT,
      dateFtt('yyyy-MM-dd hh:mm', body.NOTICE_TIME),
      body.SEGMENT_NAME_LIST,
      body.GOTO
    )
  }
  return notice
}

/**
 * 查询票价
 *
 * @param {Number} routeId 线路id
 * @param {Number} direction 方向id
 */
async function getBusPrice(routeId, direction) {
  let body = await ajaxAsync('/bus/route/today_price', {
    SUB_ROUTEID: parseInt(routeId),
    BUS_DIRECTION: parseInt(direction)
  })
  return body.PRICE
}

/**
 * 获取首末班车时间
 *
 * @param {Number} routeId 线路id
 * @param {Number} direction 方向id
 * @returns
 */
async function getFirstAndLastBusTime(routeId, direction) {
  if (window.startAndEndTime) {
    let body = await ajaxAsync('/bus/route/today_schedule', {
      SUB_ROUTEID: parseInt(routeId),
      BUS_DIRECTION: parseInt(direction)
    })
    let { FIRST_TIME, LAST_TIME } = body
    return { firstTime: FIRST_TIME, lastTime: LAST_TIME }
  } else {
    return Promise.resolve({})
  }
}

/**
 * 下一班公交车时间查询
 *
 * @param {Number} routeId 线路id
 * @param {Number} direction 方向id
 */
async function getNextBusTime(routeId, direction) {
  let nextBusTime = null
  if (window.openNextTime && window.isBusNowApis) {
    // 允许展示下一班发车时间并且有实时公交数据的请求协议
    let res = await ajaxAsync('/bus/bus/planRunTime', {
      SUBROUTEID: routeId,
      DIRECTION: direction
    })
    if (res.NEXT_TIME) {
      // nextBusTime = res.NEXT_TIME + 'split' + new Date().getTime()
      nextBusTime = res.NEXT_TIME
    }
    return nextBusTime
  } else {
    return Promise.resolve(nextBusTime)
  }
}

/**
 * 根据当前定位获取该条线路下的所有公交
 * @param {Number} routeId 线路Id
 * @param {Number} direction 方向 1上行，2下行
 * @param {String} longitude 经度
 * @param {String} latitude 维度
 */
async function getBusListByLocation(
  routeId,
  direction,
  longitude = 0,
  latitude = 0,
  stationList
) {
  let postData = {
    SUBROUTE_ID: routeId,
    TYPE: direction,
    LONGITUDE: longitude + '',
    LATITUDE: latitude + ''
  }

  let body = await ajaxAsync('/bus/now/lalo3', postData)
  let index = 0
  if (body.STAITON_ID) {
    index = stationList.findIndex((station, index) => {
      return station.sameId === body.STAITON_ID
    })
  }
  index = index === -1 ? 0 : index
  let lastStation = stationList[index - 1]
  let endStation = stationList[stationList.length - 1]
  let res = parseBusList(routeId, direction, lastStation, endStation, body)
  res.selectedIndex = index
  res.selectedStation = stationList[index]
  console.log('/bus/now/lalo3', res)
  return res
}

/**
 * 根据站点编号获取实时公交数据
 * @param {Number} routeId 线路Id
 * @param {Number} direction 方向 1上行，2下行
 * @param {StationInfoModel} station 选中的站点信息
 * @param {StationInfoModel} lastStation 选中的上一个站点信息
 * @param {StationInfoModel} endStation 最后一站站点信息
 */
async function getBusListBySameId(
  routeId,
  direction,
  station,
  lastStation,
  endStation
) {
  let postData = {
    SUBROUTE_ID: routeId,
    TYPE: direction,
    SAME_ID: station.sameId
  }

  let body = await ajaxAsync('/bus/now/sameid3', postData)
  return parseBusList(routeId, direction, lastStation, endStation, body)
}

function parseBusList(routeId, direction, lastStation, endStation, body) {
  routeId = routeId + ''
  let modelListObj = {}
  // let thisAttentionBusList = [].concat(attentionBusList)
  if (body.BUS_NOWAPIS) {
    // if (!window.prodInApp) {
    //   let testBus = [].concat(body.BUS_NOWAPIS)
    //   testBus = testBus.concat(body.BUS_NOWAPIS)
    //   testBus = testBus.concat(body.BUS_NOWAPIS)
    //   testBus = testBus.concat(body.BUS_NOWAPIS)
    //   testBus = testBus.concat(body.BUS_NOWAPIS)
    //   body.BUS_NOWAPIS = testBus
    //   console.log('~~~body.BUS_NOWAPIS~~11', body.BUS_NOWAPIS)
    // }
    body.BUS_NOWAPIS.map((bus, index) => {
      let stationId = bus.ID + ''
      if (stationId === endStation.stationId && bus.ISARRLFT !== 1) {
        // 车辆在最后一站离站不展示
        return
      }
      // bus.VEHICLE_STATE = 1
      // 车辆是到站和已离站，所以所以判断车子是否即将到站要将车子所在站点id和选中的上一个站点的id相比较
      let busModel = new BusInfoModel(
        bus.CAR_ID,
        bus.BUSCARD,
        stationId,
        bus.ISARRLFT,
        // TODO: 车辆状态
        bus.VEHICLE_STATE,
        lastStation && stationId === lastStation.stationId,
        routeId,
        direction
      )
      // 解析该辆车是否添加了下车提醒
      // if (thisAttentionBusList && thisAttentionBusList.length > 1) {
      //   let index = thisAttentionBusList.find(attentionStation => {
      //     if (
      //       attentionStation.LINE_ID === routeId &&
      //       attentionStation.LINE_TYPE === direction &&
      //       attentionStation.BUS_ID === busModel.busCard
      //     ) {
      //       busModel.setBusAttention(true)
      //       return true
      //     }
      //   })
      //   // 如果判断通过了把列表中的数据删除
      //   if (index > 0) {
      //     thisAttentionBusList.splice(index, 1)
      //   }
      // }
      busModel.setBusAttention(busIsAttention(busModel))

      let listKey = stationId + '_' + bus.ISARRLFT
      // 将公交列表按照站点编号分类
      if (modelListObj[listKey]) {
        modelListObj[listKey].push(busModel)
      } else {
        modelListObj[listKey] = [busModel]
      }
    })
  }

  let distanceList = []
  if (body.SIMPLE_DISTANCES) {
    body.SIMPLE_DISTANCES.map(info => {
      distanceList.push(new DistanceModel(info.STOP_NBR, info.DISTANCE))
    })
  }
  return { routeBusObject: modelListObj, distanceList }
}

export {
  getRouteInfo,
  getRouteNotice,
  getBusPrice,
  getFirstAndLastBusTime,
  getNextBusTime,
  getBusListByLocation,
  getBusListBySameId
}
